package com.loveprogrammer.lowercode.dna.common;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @ClassName IdGenerator
 * @Description TODO
 * @Author admin
 * @Date 2023/11/14 15:43
 * @Version 1.0
 */
public class IdGenerator {

    private static AtomicInteger id = new AtomicInteger(0);

    private static AtomicLong atomicTimeMills = new AtomicLong(0);

    private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

    public static Long getNextId() {    //并发获取不重复的时间
        while (true) {   //CAS思想
            long currentMill = atomicTimeMills.get();
            Long currentTimeMillis = Long.parseLong(LocalDateTime.now().format(formatter));
            if (currentTimeMillis > currentMill && atomicTimeMills.compareAndSet(currentMill, currentTimeMillis)) {
                return currentTimeMillis;
            }
        }
    }

}
